<template>
    <div class="crm-crmRental-container">
        <el-dialog title="修改租借" v-model="isShowDialog" >
            <el-form ref="editCrmRentalFormRef" :model="formData" :rules="formRules" label-width="100px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="租借人才" prop="talenterName">
                            <el-input v-model="formData.talenterName" placeholder="请输入租借方名称" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="租借方名称" prop="rentalName">
                            <el-input v-model="formData.rentalName" placeholder="请输入租借方名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="联系人姓名" prop="contractName">
                            <el-input v-model="formData.contractName" placeholder="请输入联系人姓名" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="手机号码" prop="contractMobile">
                            <el-input v-model="formData.contractMobile" placeholder="请输入手机号码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="开始时间" prop="rentalStartTime">
                            <el-date-picker v-model="formData.rentalStartTime" placeholder="请输入开始时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="结束时间" prop="rentalEndTime">
                            <el-date-picker v-model="formData.rentalEndTime" placeholder="请输入开始时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="租借金额" prop="rentalAmount">
                            <el-input-number v-model="formData.rentalAmount" placeholder="请输入租借金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="结算单位" prop="rentalUnit">
                            <el-select v-model="formData.rentalUnit" placeholder="请选择结算单位" clearable class="w100">
                                <el-option label="每小时" value="H"></el-option>
                                <el-option label="每天" value="D"></el-option>
                                <el-option label="每月" value="M"></el-option>
                                <el-option label="每年" value="Y"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="省份" prop="areaId">
                            <el-select v-model="formData.areaId" filterable remote 
                                @change="handleAreaChange"
                                @click="loadAreaData()"
                                :remote-method="loadAreaData" placeholder="请选择省份" clearable class="w100">
								<el-option 
									v-for="item in areas"
									:key="item.id"
									:label="item.areaName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="工作地点" prop="workLocation">
                            <el-input v-model="formData.workLocation" placeholder="请输入工作地点" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="技能要求" prop="requiredSkill">
                            <el-input v-model="formData.requiredSkill" type="textarea" :rows="5" placeholder="请输入技能要求" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { editCrmRental, renewalCrmRental } from '/@/api/crm/rental/index';
import { getCrmTalenterList } from '/@/api/crm/talenter/index';
import { getCrmAreaList } from '/@/api/crm/area/index';
export default {
    name: 'crm/rental/edit',
    setup(props, context) {
        const editCrmRentalFormRef = ref();
        const state = reactive({
            isShowDialog: false,
            talenters: [],
            areas: [],
            formData: {
                operate: 'edit',
                talenterIds: []
            },
            formRules : {
                rentalName: { required: true, message: '租借方名称不能为空', trigger: 'blur' },
                contractName: { required: true, message: '联系人姓名不能为空', trigger: 'blur' },
                contractMobile: { required: true, message: '手机号码不能为空', trigger: 'blur' },
                rentalStartTime: { required: true, message: '租借开始时间不能为空', trigger: 'blur' },
                rentalEndTime: { required: true, message: '租借结束时间不能为空', trigger: 'blur' },
                rentalAmount: { required: true, message: '租借金额不能为空', trigger: 'blur' },
                rentalUnit: { required: true, message: '结算单位不能为空', trigger: 'blur' },
                areaId: { required: true, message: '省份不能为空', trigger: 'blur' },
            }
        });

        const loadTalenterData = (query: string) => {
            getCrmTalenterList({talenterName: query, examineStatus: '2', rentalStatus: '0'}).then((res) => {
                state.talenters = res.data;
            });
        };
        const handleTalenterChange = (talenterIds) => {
            const talenters = state.talenters.filter(item => talenterIds.indexOf(item.id) !== -1);
            if(talenters.length > 0){
                state.formData.rentalStartTime = formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss');
                state.formData.rentalEndTime = formatDate(new Date(talenters[0].signEndTime + ' 00:00:00'), 'yyyy-MM-dd HH:mm:ss');
                talenters.forEach(talenter => {
                    state.formData.rentalEndTime = new Date(state.formData.rentalEndTime) > new Date(talenter.signEndTime) ? talenter.signEndTime + ' 00:00:00' : state.formData.rentalEndTime;
                })
            }
        };

        const loadAreaData = () => {
			getCrmAreaList({'parentId': '100000000000'}).then((res) => {
				if(res.code == 0){
					state.areas = res.data;
				}
			});
		}
        const handleAreaChange = (value) => {
            const area = state.areas.find(item => item.id === value);
            state.formData.areaId = area.id;
            state.formData.areaName = area.areaName;
        };
        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
            if(row){
                state.formData = Object.assign({}, row);
                state.talenters = [{id: row.talenterId, talenterName: row.talenterName}];
                //操作类型
                state.formData.operate = row.operate;
                //续期租借
                if(state.formData.operate === 'renewal'){
                    state.formData.rentalStartTime = state.formData.rentalEndTime;
                    state.formData.rentalEndTime = undefined;
                }
            }
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            editCrmRentalFormRef.value.resetFields();
            state.formData.talenterIds = [];
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            editCrmRentalFormRef.value.validate(valid => {
                if(valid){
                    let params = {
                        id: state.formData.id,
                        talenterId: state.formData.talenterId,
                        talenterName: state.formData.talenterName,
                        rentalName: state.formData.rentalName,
                        contractName: state.formData.contractName,
                        contractMobile: state.formData.contractMobile,
                        rentalStartTime: state.formData.rentalStartTime,
                        rentalEndTime: state.formData.rentalEndTime,
                        workLocation: state.formData.workLocation,
                        requiredSkill: state.formData.requiredSkill,
                        rentalAmount: state.formData.rentalAmount,
                        rentalUnit: state.formData.rentalUnit,
                        areaId: state.formData.areaId,
                        areaName: state.formData.areaName,
                        remark: state.formData.remark,
                    }
                    if(state.formData.operate === 'edit'){//修改
                        editCrmRental(params).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('保存成功');
                                context.emit('submit');
                                closeDialog();
                            }
                        });
                    }else if(state.formData.operate === 'renewal'){//续期
                        renewalCrmRental(params).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('保存成功');
                                context.emit('submit');
                                closeDialog();
                            }
                        });
                    }
                }
            });
        };
        return {
            editCrmRentalFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadTalenterData,
            handleTalenterChange,
            loadAreaData,
            handleAreaChange,
            ...toRefs(state),
        };
    },
};
</script>